package com.uzai.console.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.entity.WxpubUser;
import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.SelectVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.user.app.AppUserQuery;
import com.uzai.console.dto.user.marketingtag.*;
import com.uzai.console.dto.user.wechatuser.WechatUserQuery;
import com.uzai.console.dto.user.wxpubuser.WxpubUserQuery;
import com.uzai.console.dto.user.wxworkuser.WxworkUserQuery;
import com.uzai.console.entity.AppUser;
import com.uzai.console.entity.MarketingTag;
import com.uzai.console.entity.MerBaseConfig;
import com.uzai.console.mapper.*;
import com.uzai.console.service.user.UserService;
import com.uzai.console.service.user.MarketingTagService;
import com.uzai.console.vo.cms.base.CmsBaseInfoVo;
import com.uzai.console.vo.user.marketingtag.MarketingTagReplyVo;
import com.uzai.console.vo.user.marketingtag.MarketingTagVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuqi
 * @date 2021年09月01日 19:26
 */
@Service
public class MarketingTagServiceImpl implements MarketingTagService {

    @Autowired
    private MarketingTagMapper userTypeMapper;
    @Autowired
    private MarketingTagMapper marketingTagMapper;
    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private WxworkUserMapper wxworkUserMapper;
    @Autowired
    private WxpubUserMapper wxpubUserMapper;
    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private NormalRewardRuleMapper normalRewardRuleMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;

    /**
     * 分页查询会员标签名称列表
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param marketingTagQuery
     * @return null
     */
    public Page<MarketingTagVo> findMarketingTagByPage(MarketingTagQuery marketingTagQuery){
        //新建返回到页面的LIST对象
        List<MarketingTagVo> marketingTagVoList = new ArrayList<>();

        //执行分页查询对象
        Page<MarketingTag> page = new Page<>();
        marketingTagQuery.convert(page);
        List<MarketingTag> marketingTagList = marketingTagMapper.findByList(page, marketingTagQuery);

        if(marketingTagList != null){
            for (MarketingTag marketingTag : marketingTagList){
                MarketingTagVo marketingTagVo = new MarketingTagVo();
                BeanUtils.copyProperties(marketingTag, marketingTagVo);
                marketingTagVoList.add(marketingTagVo);
            }
        }

        //返回到页面分页对象
        Page<MarketingTagVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(marketingTagVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询会员标签详情
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param marketingTagIdDto
     * @return null
     */
    public MarketingTagVo findMarketingTagById(MarketingTagIdDto marketingTagIdDto){

        MarketingTagVo marketingTagVo = new MarketingTagVo();

        if(marketingTagIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择标签id");
        }

        MarketingTag marketingTag = marketingTagMapper.selectById(marketingTagIdDto.getId(), marketingTagIdDto.getMerId());
        if(marketingTag == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该标签不存在");
        }

        BeanUtils.copyProperties(marketingTag, marketingTagVo);

        return marketingTagVo;

    }

    /**
     * 添加会员标签
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param marketingTagDto
     * @return null
     */
    public void addMarketingTag(MarketingTagDto marketingTagDto){
        if(StringUtils.isBlank(marketingTagDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入标签名称");
        }

        //验证是否重名
        MarketingTag marketingTag_name = marketingTagMapper.selectByName(marketingTagDto.getMerId(), marketingTagDto.getName());
        if(marketingTag_name != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该标签名称已经存在");
        }

        Integer now = DateUtil.getNowTime();
        MarketingTag marketingTag = new MarketingTag();
        marketingTag.setId(IdWorker.getId());
        marketingTag.setMerId(marketingTagDto.getMerId());
        marketingTag.setName(marketingTagDto.getName());
        marketingTag.setType(Tools.getInteger(marketingTagDto.getType()));
        marketingTag.setRuleData(marketingTagDto.getRuleData());
        marketingTag.setStartTime(marketingTagDto.getStartTime());
        marketingTag.setCreateTime(now);
        marketingTag.setUpdateTime(now);
        marketingTagMapper.insert(marketingTag);

        //保持缓存
        if(marketingTag.getType().intValue() != MarketingTagTypeEnum.NORMAL_VALUE){ //常规标签没有规则数据，则不存放缓存
            String redisKey = String.format(RedisCacheKeyEnum.MARKETING_TAG.getKey(), marketingTag.getId());
            redisTemplate.opsForValue().set(redisKey, JSONObject.toJSONString(marketingTag));
        }
    }

    /**
     * 删除会员标签
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param marketingTagIdDto
     * @return null
     */
    public void deleteMarketingTag(MarketingTagIdDto marketingTagIdDto){
        if(marketingTagIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择标签id");
        }

        MarketingTag marketingTag = marketingTagMapper.selectById(marketingTagIdDto.getId(), marketingTagIdDto.getMerId());
        if(marketingTag == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该标签不存在");
        }


        List<Long> sysTagsList = new ArrayList<>();
        sysTagsList.add(marketingTagIdDto.getId());

        //查询该标签是否已经被使用
        Page<WechatUser> page_wechatUser = new Page<>();
        page_wechatUser.setCurrent(1);
        page_wechatUser.setSize(5);
        WechatUserQuery wechatUserQuery = new WechatUserQuery();
        wechatUserQuery.setMerId(marketingTagIdDto.getMerId());
        wechatUserQuery.setSysTagsList(sysTagsList);

        List<WechatUser> wechatUserList = wechatUserMapper.findByList(page_wechatUser, wechatUserQuery);
        if(wechatUserList != null && wechatUserList.size() > 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该标签已经被使用，不能删除");
        }

        //查询该标签是否已经被使用
        Page<WxworkUser> page_wxwork = new Page<>();
        page_wxwork.setCurrent(1);
        page_wxwork.setSize(5);
        WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
        wxworkUserQuery.setMerId(marketingTagIdDto.getMerId());
        wxworkUserQuery.setSysTagsList(sysTagsList);
        List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(page_wxwork, wxworkUserQuery);
        if(wxworkUserList != null && wxworkUserList.size() > 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该标签已经被使用，不能删除");
        }

        //查询该标签是否已经被使用
        Page<WxpubUser> page_wxpub = new Page<>();
        page_wxpub.setCurrent(1);
        page_wxpub.setSize(5);

        WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
        wxpubUserQuery.setMerId(marketingTagIdDto.getMerId());
        wxpubUserQuery.setSysTagsList(sysTagsList);
        List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(page_wxpub, wxpubUserQuery);
        if(wxpubUserList != null && wxpubUserList.size() > 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该标签已经被使用，不能删除");
        }

        //查询该标签是否已经被使用
        Page<AppUser> page_app = new Page<>();
        page_app.setCurrent(1);
        page_app.setSize(5);

        AppUserQuery appUserQuery = new AppUserQuery();
        appUserQuery.setMerId(marketingTagIdDto.getMerId());
        appUserQuery.setSysTagsList(sysTagsList);
        List<AppUser> appUserList = appUserMapper.findByList(page_app, appUserQuery);
        if(appUserList != null && appUserList.size() > 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该标签已经被使用，不能删除");
        }

        marketingTagMapper.deleteById(marketingTagIdDto.getId(), marketingTagIdDto.getMerId());

        //删除缓存
        String redisKey = String.format(RedisCacheKeyEnum.MARKETING_TAG.getKey(), marketingTag.getId());
        redisTemplate.delete(redisKey);

    }

    /**
     * 修改会员标签名称
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param marketingTagDto
     * @return null
     */
    public void updateMarketingTag(MarketingTagDto marketingTagDto){

        if(marketingTagDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        if(StringUtils.isBlank(marketingTagDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入标签名称");
        }

        MarketingTag marketingTag = marketingTagMapper.selectById(marketingTagDto.getId(), marketingTagDto.getMerId());
        if(marketingTag == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该标签不存在");
        }

        //验证新名字是否已经存在
        if(!marketingTagDto.getName().equals(marketingTag.getName())){ //表示修改了组名称
            //验证新名称是否存在
            MarketingTag marketingTag_name = marketingTagMapper.selectByName(marketingTagDto.getMerId(), marketingTagDto.getName());
            if(marketingTag_name != null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该组名称已经存在");
            }
        }

        Integer now = DateUtil.getNowTime();
        marketingTag.setName(marketingTagDto.getName());
        marketingTag.setRuleData(marketingTagDto.getRuleData());
        marketingTag.setStartTime(marketingTagDto.getStartTime());
        marketingTag.setUpdateTime(now);
        marketingTagMapper.updateById(marketingTag);

        //保存缓存
        String redisKey = String.format(RedisCacheKeyEnum.MARKETING_TAG.getKey(), marketingTag.getId());
        redisTemplate.opsForValue().set(redisKey, JSONObject.toJSONString(marketingTag));
    }

    /**
     * 查询所有会员类型列表
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param marketingTagQuery
     * @return null
     */
    public List<MarketingTagVo> findMarketingTagByList(MarketingTagQuery marketingTagQuery){
        //新建返回到页面的LIST对象
        List<MarketingTagVo> marketingTagVoList = new ArrayList<>();
        List<MarketingTag> marketingTagList = marketingTagMapper.findByList(marketingTagQuery);

        if(marketingTagList != null){
            for (MarketingTag marketingTag : marketingTagList){
                MarketingTagVo marketingTagVo = new MarketingTagVo();
                BeanUtils.copyProperties(marketingTag, marketingTagVo);
                marketingTagVo.setName(marketingTag.getName());
                if(!Tools.getStr(marketingTag.getName()).startsWith("SYS_")){//去掉SYS_开头的会员标签
                    marketingTagVoList.add(marketingTagVo);
                }
            }
        }

        //将分页信息复制到返回到页面的分页MO当中
        return marketingTagVoList;
    }

    /**
     * 查询所有会员标签类型列表
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param
     * @return null
     */
    public List<SelectVo> findMarketingTypeListSelect(){
        List<SelectVo> selectVoList = new ArrayList<>();
        MarketingTagTypeEnum[] marketingTagTypeEnums = MarketingTagTypeEnum.values();
        if(marketingTagTypeEnums != null && marketingTagTypeEnums.length > 0){
            for (MarketingTagTypeEnum marketingTagTypeEnum : marketingTagTypeEnums) {
                SelectVo selectVo = new SelectVo();
                selectVo.setKey(String.valueOf(marketingTagTypeEnum.getId()));
                selectVo.setValue(marketingTagTypeEnum.getDesc());
                selectVoList.add(selectVo);
            }
        }
        return selectVoList;
    }

    /**
     * 查询会员标签营销奖励回复语
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param
     * @return null
     */
    public MarketingTagReplyVo findMarketingTagReply(Long merId){
        MarketingTagReplyVo marketingTagReplyVo = new MarketingTagReplyVo();
        //查询运营商CMS基础设置信息
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.MARKETING_TAG_REPLY.getValue());
        if (merBaseConfig != null) {
            marketingTagReplyVo = JSONObject.parseObject(merBaseConfig.getVal(), MarketingTagReplyVo.class);
        }
        return marketingTagReplyVo;
    }

    /**
     * 修改会员标签营销奖励回复语
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param
     * @return null
     */
    public void updateMarketingTagReply(MarketingTagReplyDto marketingTagReplyDto){

        MarketingTagReplyVo marketingTagReplyVo = new MarketingTagReplyVo();
        BeanUtils.copyProperties(marketingTagReplyDto, marketingTagReplyVo);

        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(marketingTagReplyDto.getMerId(), MerConfigKeyEnum.MARKETING_TAG_REPLY.getValue());

        Integer now = DateUtil.getNowTime();
        //修改
        if (merBaseConfig != null){
            merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(marketingTagReplyVo)));
            merBaseConfig.setUpdateTime(now);
            merBaseConfigMapper.update(merBaseConfig);
        } else { //增加
            merBaseConfig = new MerBaseConfig();
            merBaseConfig.setId(IdWorker.getId());
            merBaseConfig.setMerId(marketingTagReplyDto.getMerId());
            merBaseConfig.setType(MerConfigTypeEnum.PRODUCTS.getValue());
            merBaseConfig.setKey(MerConfigKeyEnum.MARKETING_TAG_REPLY.getValue());
            merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(marketingTagReplyVo)));
            merBaseConfig.setCreateTime(now);
            merBaseConfig.setUpdateTime(now);
            merBaseConfigMapper.insert(merBaseConfig);
        }

        //保存到Redis当中
        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.MARKETING_TAG_REPLY.getKey(), marketingTagReplyDto.getMerId()), merBaseConfig.getVal());
    }


    /**
     * 复制会员标签
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param
     * @return null
     */
    public void copyMarketingTag(MarketingTagCopyDto marketingTagCopyDto){

        if(marketingTagCopyDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择记录");
        }

        if(StringUtils.isBlank(marketingTagCopyDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入标签名称");
        }

        //查询将要复制的会员标签
        MarketingTag marketingTag = marketingTagMapper.selectById(marketingTagCopyDto.getId(), marketingTagCopyDto.getMerId());
        if(marketingTag == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未查询到该记录");
        }

        //验证是否重名
        MarketingTag marketingTag_name = marketingTagMapper.selectByName(marketingTagCopyDto.getMerId(), marketingTagCopyDto.getName());
        if(marketingTag_name != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该标签名称已经存在");
        }

        Integer now = DateUtil.getNowTime();
        MarketingTag marketingTag_copy = new MarketingTag();
        marketingTag_copy.setId(IdWorker.getId());
        marketingTag_copy.setMerId(marketingTagCopyDto.getMerId());
        marketingTag_copy.setName(marketingTagCopyDto.getName());
        marketingTag_copy.setType(Tools.getInteger(marketingTag.getType()));
        marketingTag_copy.setRuleData(marketingTag.getRuleData());
        marketingTag_copy.setStartTime(marketingTag.getStartTime());
        marketingTag_copy.setCreateTime(now);
        marketingTag_copy.setUpdateTime(now);
        marketingTagMapper.insert(marketingTag_copy);

        //保持缓存
        if(marketingTag_copy.getType().intValue() != MarketingTagTypeEnum.NORMAL_VALUE){ //常规标签没有规则数据，则不存放缓存
            String redisKey = String.format(RedisCacheKeyEnum.MARKETING_TAG.getKey(), marketingTag_copy.getId());
            redisTemplate.opsForValue().set(redisKey, JSONObject.toJSONString(marketingTag_copy));
        }
    }

}
